
package com.hexinfo.dmpro.sparing.service.impl;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hexinfo.dmpro.common.utils.CommonConstants;
import com.hexinfo.dmpro.common.utils.ScanCommonConstants;
import com.hexinfo.dmpro.sparing.dto.TotalDTO;
import com.hexinfo.dmpro.sparing.model.HotStandbyLogSource;
import com.hexinfo.dmpro.sparing.dao.HotStandbyLogSourceMapper;
import com.hexinfo.dmpro.sparing.model.HotStandbyLogTable;
import com.hexinfo.dmpro.sparing.model.TimeFieldMatching;
import com.hexinfo.dmpro.sparing.service.HotStandbyLogSourceService;
import com.hexinfo.dmpro.sparing.service.HotStandbyLogTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 热备源级日志分析表
 *
 * @author zax
 * @date 2023-11-18 14:24:10
 */
@Service
public class HotStandbyLogSourceServiceImpl extends ServiceImpl<HotStandbyLogSourceMapper, HotStandbyLogSource> implements HotStandbyLogSourceService {

    @Autowired
    private HotStandbyLogSourceMapper hotStandbyLogSourceMapper;
    @Autowired
    private HotStandbyLogTableService hotStandbyLogTableService;

    @Override
    public Page queryList(Page page, HotStandbyLogSource hotStandbyLogSource) {
        LambdaQueryWrapper<HotStandbyLogSource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(HotStandbyLogSource::getDel,CommonConstants.STATUS_NORMAL);
        Page returnPage = this.baseMapper.selectPage(page, wrapper);
        return returnPage;
    }

    @Override
    public List<HotStandbyLogSource> queryTaskDate(String sourceName, String taskDate) {
        LambdaQueryWrapper<HotStandbyLogSource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(HotStandbyLogSource::getDel,CommonConstants.STATUS_NORMAL)
                .eq(HotStandbyLogSource::getSourceName,sourceName)
                .eq(HotStandbyLogSource::getTaskDate,taskDate)
                .orderByDesc(HotStandbyLogSource::getCreateTime);
        return this.baseMapper.selectList(wrapper);
    }

    /**
     * 按照条件获取数据
     * @param page
     * @param hotStandbyLogSource
     * @return
     */
    @Override
    public IPage getHotStandbyLogSources(Page page, HotStandbyLogSource hotStandbyLogSource) {
        return hotStandbyLogSourceMapper.getHotStandbyLogSources(page, hotStandbyLogSource);
    }

    /**
     * 获取当天全部源的成功、失败、进行中数量
     */
    @Override
    public TotalDTO getStateAllNum() {
        return hotStandbyLogSourceMapper.getStateAllNum(DateUtil.format(DateUtil.date(), "yyyyMMdd"),
                ScanCommonConstants.ClusterName.YWC.value,
                ScanCommonConstants.ClusterName.DZX.value,
                ScanCommonConstants.ClusterName.JXZ.value,
                ScanCommonConstants.ClusterName.SB.value);
    }

    /**
     *  新增日志分析记录--获取id
     */
    @Override
    public String addHotStandbyLogSource(String source) {
        Date date = DateUtil.date();
        HotStandbyLogSource hotStandbyLogSource = new HotStandbyLogSource();
        if(StrUtil.isBlank(source)){
            hotStandbyLogSource.setSourceName("无源");
        }else {
            hotStandbyLogSource.setSourceName(source);
        }
        hotStandbyLogSource.setTaskDate(DateUtil.format(date, "yyyyMMdd"));
        hotStandbyLogSource.setTaskState(ScanCommonConstants.ClusterName.JXZ.value);
        hotStandbyLogSource.setHotStandbyStaTime(DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
        hotStandbyLogSource.setHotStandbyTimeData("【规则过滤】" + DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")+"--");
        hotStandbyLogSource.setHotStandbyTime("0");
        save(hotStandbyLogSource);
        return hotStandbyLogSource.getId();
    }

    /**
     * 日志分析记录修改--用时详情修改、同步范围起始时间--LS过滤步骤
     */
    @Override
    public void upLSSyncRange(String logId,String syncRangeStart,String syncRangeEnd,String str) {
        HotStandbyLogSource hotStandbyLogSource = getById(logId);
        hotStandbyLogSource.setSyncRangeStartTime(syncRangeStart);
        hotStandbyLogSource.setSyncRangeEndTime(syncRangeEnd);
        hotStandbyLogSource.setHotStandbyTimeData(hotStandbyLogSource.getHotStandbyTimeData()+str);
        updateById(hotStandbyLogSource);
    }

    /**
     * 日志分析记录修改--用时详情修改，表数量/HDFS数量--同步步骤
     */
    @Override
    public void upSyncTableHdfsNumber(String logId,String tableHdfsNumber,String str) {
        HotStandbyLogSource hotStandbyLogSource = getById(logId);
        hotStandbyLogSource.setTableHdfsNumber(tableHdfsNumber);
        hotStandbyLogSource.setHotStandbyTimeData(hotStandbyLogSource.getHotStandbyTimeData()+str);
        updateById(hotStandbyLogSource);
    }

    /**
     * 日志分析记录修改--任务状态，热备用时，结束时间--热备结束
     */
    @Override
    public void upTaskState(String logId,String state) {
        Date date = DateUtil.date();
        HotStandbyLogSource hotStandbyLogSource = getById(logId);
        String timeStr = getTimeStr(hotStandbyLogSource.getHotStandbyTimeData());
        //查询日志ID下全部的表信息做源总量和目标总量计算
        //源总数
        Long numSource =  0L;
        //目标总数
        Long numTarget =  0L;
        LambdaQueryWrapper<HotStandbyLogTable> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StrUtil.isNotBlank(logId),HotStandbyLogTable::getSourceId,logId)
                .eq(HotStandbyLogTable::getDel,CommonConstants.STATUS_NORMAL);
        List<HotStandbyLogTable> tableList = hotStandbyLogTableService.getBaseMapper().selectList(wrapper);
        if(ObjectUtil.isNotEmpty(tableList)){
            for (HotStandbyLogTable table: tableList) {
                if(ObjectUtil.isNotEmpty(table.getSourceCountNumber())){
                    numSource += table.getSourceCountNumber();
                }
                if(ObjectUtil.isNotEmpty(table.getTargetCountNumber())){
                    numTarget += table.getTargetCountNumber();
                }
            }
        }
        hotStandbyLogSource.setSourceCountNumber(numSource);
        hotStandbyLogSource.setTargetCountNumber(numTarget);
        hotStandbyLogSource.setTaskState(state);
        hotStandbyLogSource.setHotStandbyTime(DateUtil.formatBetween(DateUtil.parse(hotStandbyLogSource.getHotStandbyStaTime(),"yyyy-MM-dd HH:mm:ss"),date, BetweenFormater.Level.SECOND));
        hotStandbyLogSource.setHotStandbyEndTime(DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
        hotStandbyLogSource.setHotStandbyTimeData("----------------------模块耗时---------------------"+ "\n"+timeStr
                +"-----------------开始时间--结束时间-----------------"+ "\n" +hotStandbyLogSource.getHotStandbyTimeData());
        updateById(hotStandbyLogSource);
    }

    /**
     * 获取每个模块执行时间
     * @param hotStandbyTimeData
     * @return
     */
    private String getTimeStr(String hotStandbyTimeData) {
        String str = "";
        String[] split = hotStandbyTimeData.split("\n");
        for (String s : split) {
            if (s.length()>6){
                String[] split1 = s.substring(6).split("--");
                if (split1.length == 2){
                    str += s.substring(0,6)+DateUtil.formatBetween(DateUtil.parse(split1[0]), DateUtil.parse(split1[1]), BetweenFormater.Level.SECOND) +"\n";
                }
            }
        }
        return str;
    }

    /**
     * 日志分析记录修改--用时详情修改
     */
    @Override
    public void upHotLog(String logId,String str) {
        HotStandbyLogSource hotStandbyLogSource = getById(logId);
        hotStandbyLogSource.setHotStandbyTimeData(hotStandbyLogSource.getHotStandbyTimeData()+str);
        updateById(hotStandbyLogSource);
    }

    @Override
    public List<HotStandbyLogSource> sourceHotBackupState() {
        return hotStandbyLogSourceMapper.sourceHotBackupState();
    }

    @Override
    public List<HotStandbyLogSource> sourceHotBackupStateToDay() {
        return hotStandbyLogSourceMapper.sourceHotBackupStateToDay();
    }

    @Override
    public List<HotStandbyLogSource> sourceHotBackupStateTwo() {
        return hotStandbyLogSourceMapper.sourceHotBackupStateTwo();
    }

    @Override
    public HotStandbyLogSource querySourceName(String sourceName) {
        LambdaQueryWrapper<HotStandbyLogSource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(HotStandbyLogSource::getSourceName,sourceName);
        wrapper.eq(HotStandbyLogSource::getDel,CommonConstants.STATUS_NORMAL);
        wrapper.orderByDesc(HotStandbyLogSource::getCreateTime);
        List<HotStandbyLogSource> hotStandbyLogSources = this.baseMapper.selectList(wrapper);
        return hotStandbyLogSources.isEmpty() ? null : hotStandbyLogSources.get(0);
    }
}
